define [
	'jquery'
	'helper'
	'template'
	'lib/jquery.couch.js'
], ($, H) ->
	S = {}
	$.fn.mb_donation_detail = (SamCtx) ->
	
		# Global variable
		$this = $(@)
		S = SamCtx
		$tpl = $('.tpl', $this).hide()
		
		# Initialization and table creation
		unless @mb_plugin()
			@mb_plugin 'donation_detail'
			
			# Main subscription event to handle published donation id and display it in the current page
			$.subscribe 'mb.donation', (e, arg) =>
				donationID = arg['id']
				
				# Open couch document for reading
				H.db().openDoc donationID,
					success: (doc) ->
						doc.cash_yn = if doc.cash then 'Yes' else 'No'
						doc.donation_amount = "$#{parseFloat(doc.donation_amount).toFixed(2)}"
						
						# Acquire the template for the form and fill in content
						$('.content', $this).empty().append S.content $tpl, doc
						
						# Remove all the fields (rows) that are blank
						$('.content tr > td:odd', $this).each ->
							$(@).parent().remove() if $(@).text().length is 0

				# Define click event handling for Print Receipt button
				$('[name="view_receipt"]', $this).on 'click', ->
					$.publish 'mb.donation',
						id: donationID
						for: 'receipt'
					S.app.setLocation '#/view_receipt'
					
				return
		return @
	return
